// GNEncode.cpp: implementation of the GNEncode class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "GNEncode.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

GNEncode::GNEncode(unsigned char *pucKey, int iLen)
	: m_cEncode(pucKey, iLen)
{
}

GNEncode::~GNEncode()
{
}



void GNEncode::EncodeString(gnstring &s)
{
	_EncodeOrDecodeString(s, true);
}

void GNEncode::DecodeString(gnstring &s)
{
	_EncodeOrDecodeString(s, false);
}

void GNEncode::_EncodeOrDecodeString(gnstring &s, bool bEncode)
{
	int i, iLen;

	if (s.empty())
	{
		return;
	}
	iLen = 8 - (s.length() % 8);
	if (iLen == 8)
	{
		iLen = 0;
	}
	for (i = 0; i < iLen; ++i)
	{
		s += _T(" ");
	}

	if (bEncode)
	{
		m_cEncode.Encrypt((unsigned char*)s.data(), (unsigned char*)s.data(), s.length() * sizeof(gnchar));
	}
	else
	{
		m_cEncode.Decrypt((unsigned char*)s.data(), (unsigned char*)s.data(), s.length() * sizeof(gnchar));
		StringUtil::trimRight(s);
	}
}


void GNEncode::WEncodeString(wstring &s)
{
	_WEncodeOrDecodeString(s, true);
}

void GNEncode::WDecodeString(wstring &s)
{
	_WEncodeOrDecodeString(s, false);
}

void GNEncode::_WEncodeOrDecodeString(wstring &s, bool bEncode)
{
	int i, iLen;

	if (s.empty())
	{
		return;
	}
	iLen = 8 - (s.length() % 8);
	if (iLen == 8)
	{
		iLen = 0;
	}
	for (i = 0; i < iLen; ++i)
	{
		s += L" ";
	}

	if (bEncode)
	{
		m_cEncode.Encrypt((unsigned char*)s.data(), (unsigned char*)s.data(), s.length() * sizeof(wchar_t));
	}
	else
	{
		m_cEncode.Decrypt((unsigned char*)s.data(), (unsigned char*)s.data(), s.length() * sizeof(wchar_t));
		WStringUtil::trimRight(s);
	}
}
